package com.dt.app.controller.test;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dt.app.common.constant.ConstantCode;
import com.dt.app.exception.ExcelException;
import com.dt.app.modules.sys.entities.SysUserEntity;
import com.dt.app.modules.test.vo.SchoolCourseSelectionCount;
import com.dt.app.modules.test.vo.SchoolCourseSelectionExcel;
import com.dt.export.data.SysUserData;
import com.dt.export.utils.ExcelUtils;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.time.DateFormatUtils;

import javax.servlet.http.HttpServletResponse;
import javax.validation.Valid;

import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.servlet.ModelAndView;

import java.util.*;

import com.dt.app.common.response.ResultUtil;
import com.dt.app.modules.test.entities.SchoolCourseSelection;
import com.dt.app.modules.test.vo.SchoolCourseSelectionBean;
import com.dt.app.api.test.service.ISchoolCourseSelectionService;
import com.dt.app.controller.base.BaseController;
import org.springframework.web.bind.annotation.RestController;

/**
 * <p>
 *  前端控制器
 *  七年级的科目选择:
 * 阅读与写作90人，数学思维90人，口语与写作90人，体育60人，美术40人，音乐40人，信息40人，书法40人
 * 八年级的科目选择:
 * 阅读与写作60人，数学思维60人，口语与写作60人，体育60人，美术40人，音乐40人，信息40人，书法40人,物理兴趣50人
 * </p>
 * @author 鸿源塔基
 * @since 2024-02-22
 */
@RestController
@RequestMapping("api/v1/test/schoolCourseSelection")
public class SchoolCourseSelectionController extends BaseController{
    @Autowired
    private ISchoolCourseSelectionService schoolCourseSelectionService;
    private static final LinkedHashMap<String,Integer> XuanKeSl7_1 = new LinkedHashMap<>(){{
put("英语单词速记",51);put("语文阅读与分享",51);put("书法1",51);put("数学基础提升",51);put("体能与篮球",56);put("数学运算能力训练",51);put("数学思维训练",51);put("信息基础与技术",51);
        put("语文写作训练",51);put("英语口语与作文",51);
    }};
    private static final LinkedHashMap<String,Integer> XuanKeSl7_2 = new LinkedHashMap<>(){{
put("信息编程",51);put("英语基础提升",51);put("书法2",51);put("历史名人传",51);put("毽球与跳绳",56);put("剪纸艺术",51);put("乐器鉴赏",51);put("生物与实验",51);
        put("地理与生活",51);put("音乐与乐理",51);
    }};
    private static final LinkedHashMap<String,Integer> XuanKeSl8_1 = new LinkedHashMap<>(){{
put("语文写作训练",51);put("书法",51);put("数学巧算速算",51);put("美术",51);put("数学图像分解",51);put("物理思维拓展",55);put("体能与篮球",55);put("音乐鉴赏",55);
    }};
    private static final LinkedHashMap<String,Integer> XuanKeSl8_2 = new LinkedHashMap<>(){{
put("信息编程",55);put("数学思维训练",51);put("语文阅读分享",51);put("英语阅读分享",51);put("物理兴趣培养",55);put("英语听说技巧",51);put("英语写作训练",51);put("跳绳与技巧",55);
    }};
    private static final List<SchoolCourseSelectionBean> Beans = new ArrayList<>();

    @ApiOperation(value = "列表")
    @RequestMapping("list")
    public ResultUtil<List<SchoolCourseSelectionCount>> list(SchoolCourseSelectionBean request){
        if(request.getGrade()!=null&&request.getGrade().length()>0){
            return this.xkList(request);
        }
        List<SchoolCourseSelectionCount> returnList=new ArrayList<>();
        if(StringUtils.isEmpty(request.getName()) && StringUtils.isEmpty(request.getClassName())){
            int yxzsl = schoolCourseSelectionService.getCountTotal();
            LinkedHashMap<String,SchoolCourseSelectionCount> scsc = getKxsl();
            scsc.forEach((key,value)->{
                returnList.add(value);
            });
            ResultUtil resultUtil = ResultUtil.success(returnList);
            resultUtil.setMsg("已报名总人数："+yxzsl);
            return resultUtil;
        }
        QueryWrapper<SchoolCourseSelection> wrapper = new QueryWrapper<>();
        if(request.getName()!=null)wrapper.eq("name",request.getName());
        if(request.getClassName()!=null)wrapper.eq("class_name",request.getClassName());
        List<SchoolCourseSelection> entityList=schoolCourseSelectionService.list(wrapper);
        if(entityList.isEmpty()) {
            return ResultUtil.success(returnList);
        }
        for (SchoolCourseSelection s:entityList){
            SchoolCourseSelectionCount ssc=new SchoolCourseSelectionCount();
            ssc.setCourse(s.getCourse());ssc.setGrade(s.getGrade());ssc.setName(s.getName());
            //ssc.setSlZg();
            //ssc.setSlYx();
            returnList.add(ssc);
        }
        return ResultUtil.success(returnList);
    }

    @PostMapping("save")
    @ApiOperation(value = "新增")
    public ResultUtil save(@RequestBody @Valid SchoolCourseSelectionBean bean){
        bean.toSetGrade();
        SchoolCourseSelection entity1 = new SchoolCourseSelection();
        SchoolCourseSelection entity2 = new SchoolCourseSelection();
        BeanUtils.copyProperties(bean,entity1);
        BeanUtils.copyProperties(bean,entity2);
        if(bean.getGrade().equals("七年级")){
            int sl1=schoolCourseSelectionService.getCount(bean.getGrade(),bean.getCourse71());
            int sl2=schoolCourseSelectionService.getCount(bean.getGrade(),bean.getCourse72());
            if( sl1 >= XuanKeSl7_1.get(bean.getCourse71())){
                return ResultUtil.error("保存失败，"+bean.getCourse71()+"，限制人数："+XuanKeSl7_1.get(bean.getCourse71()));
            }
            if( sl2 >= XuanKeSl7_2.get(bean.getCourse72())){
                return ResultUtil.error("保存失败，"+bean.getCourse72()+"，限制人数："+XuanKeSl7_2.get(bean.getCourse72()));
            }
            entity1.setCourse(bean.getCourse71());
            entity2.setCourse(bean.getCourse72());
        }else{
            int sl1=schoolCourseSelectionService.getCount(bean.getGrade(),bean.getCourse81());
            int sl2=schoolCourseSelectionService.getCount(bean.getGrade(),bean.getCourse82());
            if( sl1 >= XuanKeSl8_1.get(bean.getCourse81())){
                return ResultUtil.error("保存失败，"+bean.getCourse81()+"，限制人数："+XuanKeSl8_1.get(bean.getCourse81()));
            }
            if( sl2 >= XuanKeSl8_2.get(bean.getCourse82())){
                return ResultUtil.error("保存失败，"+bean.getCourse82()+"，限制人数："+XuanKeSl8_2.get(bean.getCourse82()));
            }
            entity1.setCourse(bean.getCourse81());
            entity2.setCourse(bean.getCourse82());
        }
        //entity.setCreateTime(LocalDateTime.now());entity.setDeleted(0);
        List<SchoolCourseSelection> scss = schoolCourseSelectionService.getEntitys(bean.getClassName(),bean.getName());
        if(scss!=null && scss.size()>1){
            entity1.setSchoolCourseSelectionId(scss.get(0).getSchoolCourseSelectionId());
            entity2.setSchoolCourseSelectionId(scss.get(1).getSchoolCourseSelectionId());
            schoolCourseSelectionService.updateById(entity1);
            schoolCourseSelectionService.updateById(entity2);
        }else{
            schoolCourseSelectionService.save(entity1);
            schoolCourseSelectionService.save(entity2);
        }
        return ResultUtil.success();
    }

    private ResultUtil<List<SchoolCourseSelectionCount>> xkList(SchoolCourseSelectionBean request){
        if(request.getGrade().equals("1")) {
            ResultUtil resultUtil= ResultUtil.success();
            resultUtil.setMsg("请选择年级、课程。");
            return resultUtil;
        }
        List<SchoolCourseSelection> scss = schoolCourseSelectionService.getList(request.getGrade(),request.getCourse());
        List<SchoolCourseSelectionCount> rss = new ArrayList<>();
        if(scss!=null || scss.size()>0){
            for(SchoolCourseSelection s:scss){
                SchoolCourseSelectionCount b=new SchoolCourseSelectionCount();
                BeanUtils.copyProperties(s,b);
                rss.add(b);
            }
        }
        ResultUtil resultUtil= ResultUtil.success(rss);
        resultUtil.setMsg("可报人数："+getKxsl(request.getGrade(),request.getCourse())+" ; 已报人数："+scss.size());
        return resultUtil;
    }
    @GetMapping("getById/{id}")
    @ApiOperation(value = "id查询")
    public ResultUtil<SchoolCourseSelectionBean> getById(@PathVariable String id){
        SchoolCourseSelection entity = schoolCourseSelectionService.getById(id);
        if(entity!=null){
            SchoolCourseSelectionBean bean = schoolCourseSelectionService.getBean(entity);
            return ResultUtil.success(bean);
        }
        return ResultUtil.error("没有找到对象");
    }

    @PutMapping("update")
    @ApiOperation(value = "修改")
    public ResultUtil update(@RequestBody @Valid SchoolCourseSelectionBean bean){
        SchoolCourseSelection entity1 = new SchoolCourseSelection();
        SchoolCourseSelection entity2 = new SchoolCourseSelection();
        BeanUtils.copyProperties(bean,entity1);
        BeanUtils.copyProperties(bean,entity2);
        schoolCourseSelectionService.updateById(entity1);
        schoolCourseSelectionService.updateById(entity2);
        return ResultUtil.success();
    }

    @ApiOperation(value = "删除")
    @DeleteMapping("delete/{id}")
    public ResultUtil delete(@PathVariable Long id){
        schoolCourseSelectionService.removeById(id);
        return ResultUtil.success();
    }
    public LinkedHashMap<String,SchoolCourseSelectionCount> getKxsl(){
        List<SchoolCourseSelectionCount> counts=schoolCourseSelectionService.getCounts();
        LinkedHashMap<String,SchoolCourseSelectionCount> returnHM = new LinkedHashMap<>();
        addTo("七年级",XuanKeSl7_1,counts, returnHM);
        addTo("七年级",XuanKeSl7_2,counts, returnHM);
        addTo("八年级",XuanKeSl8_1,counts, returnHM);
        addTo("八年级",XuanKeSl8_2,counts, returnHM);
        return returnHM;
    }
    private void addTo(String grade, LinkedHashMap<String,Integer> nowHM,List<SchoolCourseSelectionCount> counts, LinkedHashMap<String,SchoolCourseSelectionCount> returnHM){
        nowHM.forEach((key,value)->{
            SchoolCourseSelectionCount cot=new SchoolCourseSelectionCount(grade,key,value);
            for(SchoolCourseSelectionCount s:counts){
                if(key.equals(s.getCourse()) && grade.equals(s.getGrade())){
                    cot.setSlYx(s.getSlYx());
                    break;
                }
            }
            cot.setSlZg(value);
            returnHM.put(grade+" "+key,cot);
        });
    }
    private Integer getKxsl(String grade,String course){
        if(grade.equals("七年级")){
            Integer sl = XuanKeSl7_1.get(course);if(sl!=null) return sl;
            sl = XuanKeSl7_2.get(course);if(sl!=null) return sl;
        }else{
            Integer sl = XuanKeSl8_1.get(course);if(sl!=null) return sl;
            sl = XuanKeSl8_2.get(course);if(sl!=null) return sl;
        }
        return 0;
    }
    @RequestMapping("getKcKxsl")
    @ApiOperation(value = "获取可选课程数量")
    public ResultUtil<LinkedHashMap<String,List<SchoolCourseSelectionCount>>> getKxkc(){
        List<SchoolCourseSelectionCount> counts=schoolCourseSelectionService.getCounts();
        LinkedHashMap<String,List<SchoolCourseSelectionCount>> returnHM = new LinkedHashMap<>();
        addTo2("七年级","周二",XuanKeSl7_1,counts, returnHM);
        addTo2("七年级","周三",XuanKeSl7_2,counts, returnHM);
        addTo2("八年级","周二",XuanKeSl8_1,counts, returnHM);
        addTo2("八年级","周三",XuanKeSl8_2,counts, returnHM);
        return ResultUtil.success(returnHM);
    }
    private void addTo2(String grade,String zj, LinkedHashMap<String,Integer> nowHM,List<SchoolCourseSelectionCount> counts, LinkedHashMap<String,List<SchoolCourseSelectionCount>> returnHM){
        List<SchoolCourseSelectionCount> sscs=new ArrayList();
        returnHM.put(grade+zj,sscs);
        nowHM.forEach((key,value)->{
            SchoolCourseSelectionCount cot=new SchoolCourseSelectionCount(grade,key,value);
            for(SchoolCourseSelectionCount s:counts){
                if(key.equals(s.getCourse()) && grade.equals(s.getGrade())){
                    cot.setSlYx(s.getSlYx());
                    break;
                }
            }
            cot.setSlZg(value);
            sscs.add(cot);
        });
    }

    @PostMapping("exportAll")
    @ApiOperation(value = "导出全部报名信息")
    public void export(HttpServletResponse response,@RequestBody @Valid SchoolCourseSelectionBean request) {
        String grade=request.getGrade(), course=request.getCourse();
        List<SchoolCourseSelection> scss = schoolCourseSelectionService.getList(grade,course);
        List<String> columns=new ArrayList<>();
        columns.add("className");columns.add("name");
        if(scss!=null || scss.size()>0){
            List<SchoolCourseSelectionExcel> dataList = new ArrayList<>();
            for(SchoolCourseSelection s:scss){
                SchoolCourseSelectionExcel b=new SchoolCourseSelectionExcel();
                BeanUtils.copyProperties(s,b);
                dataList.add(b);
            }
            try {
                ExcelUtils.exportExcel(response,grade+course,"可报："+getKxsl(grade,course)+" ; 已报："+scss.size(), SchoolCourseSelectionExcel.class,dataList,columns);
            } catch (Exception e) {
                throw new ExcelException("表格导出异常");
            }
        }
    }
}